package cn.frh.user.interceptor;

import cn.frh.basic.jwt.JwtUtils;
import cn.frh.basic.jwt.LoginData;
import cn.frh.basic.jwt.Payload;
import cn.frh.basic.jwt.RsaUtils;
import cn.frh.system.annotation.PreAuthorize;
import cn.frh.system.mapper.PermissionMapper;
import cn.frh.user.domain.Logininfo;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.List;
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token !=null){

            Logininfo logininfo = null;
            try {
                //获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                // 私钥
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                //获取登录信息
                logininfo = payload.getLoginData().getLogininfo();
            } catch (ExpiredJwtException e) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println("{\"success\":false,\"msg\":\"timeOut\"}");
                return false;
            }
            //Object o = redisTemplate.opsForValue().get(token);//Longininfo对象


                //刷新过期时间 实现不了
                //redisTemplate.opsForValue().set(token,o,30, TimeUnit.MINUTES);
                if (logininfo.getType() == 1){//说明是前台用户 说明不需要验证权限
                    return true;
                }
                //管理员 有权限 需要验证权限
                //1.获取当前登录人的访问接口的自定义注解sn
                HandlerMethod method = (HandlerMethod) handler;
                PreAuthorize authorize = method.getMethodAnnotation(PreAuthorize.class);
                if (authorize == null){//没有注解
                    return true;
                }else {//有注解 验证
                    //获取sn属性值
                    String sn = authorize.sn();
                    //2.获取当前登录人的所有权限sn
                    List<String> myPermissions = permissionMapper.getPermissionsByLogininfoId(logininfo.getId());
                    //3.判断包含是否有权限 有 放行 没有 不放心返回信息
                    if (myPermissions.contains(sn)){
                        return true;
                    }else {
                        //没有权限访问
                        response.setContentType("application/json;charset=UTF-8");
                        response.getWriter().println("{\"success\":false,\"msg\":\"noPermissions\"}");
                        return false;
                    }
                }

            }
        //如果token和o都为空 那么需要重新登录
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");
        return false;
    }
}
